package captcha

import (
	"egin/pkg/config"

	"image/color"
	"strings"
	"sync"

	"github.com/mojocn/base64Captcha"
)

// 设置自带的store
var store = base64Captcha.DefaultMemStore
var captchaConfigOnce sync.Once
var captcha *base64Captcha.Captcha

//生成验证码
func CaptMake() (id, b64s string, err error) {

	// 配置验证码信息
	captchaConfigOnce.Do(func() {

		captchaConfig := base64Captcha.DriverString{
			Height: config.C().Captcha.Height,
			Width:  config.C().Captcha.Width,

			NoiseCount:      config.C().Captcha.NoiseCount,
			ShowLineOptions: config.C().Captcha.OptionShowHollowLine | config.C().Captcha.OptionShowSlimeLine | config.C().Captcha.OptionShowSineLine,
			Length:          config.C().Captcha.Length,
			Source:          config.C().Captcha.Source,
			BgColor: &color.RGBA{
				R: config.C().Captcha.BgColor.R,
				G: config.C().Captcha.BgColor.G,
				B: config.C().Captcha.BgColor.B,
				A: config.C().Captcha.BgColor.A,
			},
		}

		driver := captchaConfig.ConvertFonts()
		captcha = base64Captcha.NewCaptcha(driver, store)
	})

	lid, lb64s, lerr := captcha.Generate()
	return lid, lb64s, lerr
}

//验证captcha是否正确
func CaptVerify(id string, capt string) bool {

	v := store.Get(id, true)
	if v == "" || capt == "" {
		return false
	}
	if strings.EqualFold(v, capt) {
		return true
	} else {
		return false
	}

}
